/*
    Copyright 2012 Peter Pratscher

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

using System.Collections.Generic;
using System.IO;

namespace LicenseAdder.Model
{
    public static class VbLicenseAdder
    {
        public static void ProcessFile(string fileName, List<string> licenseText)
        {
            List<string> fileContent = new List<string>(File.ReadAllLines(fileName));

            RemoveExistingHeader(fileContent);

            fileContent.Insert(0, "");

            licenseText.Reverse();
            foreach (string line in licenseText)
            {
                fileContent.Insert(0, "' " + line);
            }

            File.WriteAllLines(fileName, fileContent.ToArray());
        }

        private static void RemoveExistingHeader(List<string> fileContent)
        {
            bool inMultiLineComment = false;

            int commentStartIndex = -1, commentEndIndex = -1;

            for (int i = 0; i < fileContent.Count; i++)
            {
                if (!fileContent[i].Trim().StartsWith(@"'") && !inMultiLineComment)
                {
                    return;
                }

                if (fileContent[i].Trim().StartsWith(@"'") && !inMultiLineComment)
                {
                    commentStartIndex = i;
                    inMultiLineComment = true;
                }

                if (!fileContent[i].Trim().StartsWith(@"'") && inMultiLineComment)
                {
                    commentEndIndex = i - 1;
                    break;
                }
            }

            if (commentStartIndex != -1 && commentEndIndex != -1)
            {
                for (int i = commentStartIndex; i <= commentEndIndex; i++)
                {
                    fileContent.RemoveAt(commentStartIndex);
                }
            }

            //Remove empty lines at the beginning of the file
            while (fileContent.Count > 0 && string.IsNullOrEmpty(fileContent[0]))
            {
                fileContent.RemoveAt(0);
            }
        }
    }
}
